package com.air.controller;

import com.air.config.Result;
import com.air.exception.ParamsErrorException;
import com.air.service.MessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

@Controller
public class MessageController {

    @Autowired
    MessageService messageService;

    /**
     * 发送验证码
     */
    @RequestMapping(value = "/sendSms")
    @ResponseBody
    public void sendSms(@RequestParam("phone") String phone,
                         HttpSession session) {

        String code= randomCode();
        System.out.println("电话："+phone+"验证码"+code);
        session.setAttribute(phone,code);

        messageService.sendSms(phone,code);

        try {
            final Timer timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    String yxcode1 =  (String) session.getAttribute(phone);
                    if(StringUtils.isNotEmpty(yxcode1)){
                        session.removeAttribute(phone);
                    }
                    timer.cancel();
                }
            },5*60*1000);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
